package com.jml.service;

import lombok.extern.slf4j.Slf4j;
import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
public class SeckillRedisService {

    @Autowired
    @Qualifier("redissonClient1")
    private RedissonClient redissonClient1;
    @Autowired
    @Qualifier("redissonClient2")
    private RedissonClient redissonClient2;
    @Autowired
    @Qualifier("redissonClient3")
    private RedissonClient redissonClient3;

    @RequestMapping("/redlock/seckilRedisLock")
    public String seckilRedlock(Long commodityId) {
        RLock lock1 = redissonClient1.getLock("seckilRedisLock");
        RLock lock2 = redissonClient2.getLock("seckilRedisLock");
        RLock lock3 = redissonClient3.getLock("seckilRedisLock");
        RedissonRedLock lock = new RedissonRedLock(lock1, lock2, lock3);
        try {
            //获取锁,两个参数:获取锁的超时时间,续约时间,
            // 其实底层把等待时间/3,等待时间就是这个数值的1/3,如果小于1就取值1,就是20
            // 其实底层将续约时间*2过期时间就是这个时间的两倍,就是120
            boolean res = lock.tryLock(60, 60, TimeUnit.SECONDS);
        } catch (Exception e) {

        } finally {
            if (lock != null) {
                // 释放锁
                lock.unlock();
            }
        }
        return "ok";
    }
}
